# To change this template, choose Tools | Templates
# and open the template in the editor.
require 'logger'
require 'FileUtils'

# The builder class has primitive functions to checkout the Rollback project and build it.
class Builder
  attr_accessor :svnPath, :projectPath, :svnUserName, :svnPassword, :projectName
  @@log = Logger.new(STDOUT)
  @svnCmdPrefix = ""

  # initialize the builder object
  def initialize(svnRepoPath,svnPath,svnUsername,svnPassword,projectPath,projectName)
    @svnRepoPath = svnRepoPath
    @svnPath = svnPath
    @svnExePath = svnPath + "/svn.exe"
    @svnVersionCmd = svnPath + "/svnversion.exe"
    @svnUsername = svnUsername
    @svnPassword = svnPassword
    @projectPath = projectPath
    @projectName = projectName
    @svnCmdPrefix =  " --username " + @svnUsername + " --password " + @svnPassword + " --non-interactive --trust-server-cert "
  end

  # update or checkout the project from SVN repository.
  # cd to the directory where the project was checked out
  def updateOrCheckoutProject(cleanBuild)
    path = @projectPath + "/" + @projectName
    rmdir(path) if (cleanBuild)
    if File.exist?(path) && File.directory?(path)
      # project directory already exists, just update it
      chdir(@projectPath)
      chdir(@projectName)
      #runSvnCommand("update ")
    else
      # project directory does not exist, checkout a fresh copy
      makedir(@projectPath)
      chdir(@projectPath)
      runSvnCommand("checkout " +@svnRepoPath + " " +@projectName)
      chdir(@projectName)
    end
  end

  # Update the SVN version info in the code so that the build step picks it up
  def updateSvnInfoInSourceCode()
    #get the SVN revision number
    version = `#{@svnVersionCmd}`
    version = version.chomp
    version = version.sub(":","-")
    @@log.info("SVN version number is: " + version)
    svnFileName = "RollbackUI/src/SVNVersionInfo.cs"
    svnFile = File.open(svnFileName,"r")
    lines = svnFile.readlines
    svnFile.close()
    File.chmod(0777,svnFileName);
    outFile = File.open(svnFileName,"w")
    #lines.gsub(/\$Rev: (\d+)/m,"777")
    #lines.gsub(/using/m,"777")
    lines.each do |l|
      l = l.gsub(/\$Rev: (\d+)/,"$Rev: " +version)
      outFile.write(l)
    end
    outFile.close()
    return version
    #puts(lines)
  end
  
  # Run an SVN command in a standard way
  def runSvnCommand(svnCmd)
    cmd = @svnExePath + @svnCmdPrefix + svnCmd
    @@log.info("Running SVN command <" + cmd + ">")
    system(cmd)
    @@log.info("Finished SVN comman <"+cmd +">")
  end

  def chdir(dir)
    @@log.info("Changing to dir <"+dir+">")
    Dir.chdir(dir)
	#@@log.info("Current directory is <"+Dir.getwd() +">")
  end

  def makedir(dir)
    @@log.info("Creating dir <"+dir+">")
    FileUtils.mkdir_p(dir)
  end

  def rmdir(dir)
    @@log.info("Deleting directory <"+dir +">");
    FileUtils.remove_dir(dir, true)
  end

  # Create the installer file with the right version number as the prefix
  def makeInstaller(svnVersionNumber)
    @@log.info("Creating installer.")
    assemblyVersion = ''
    f = File.open('RollbackUI/Properties/AssemblyInfo.cs')
    line = ''
    while(line = f.gets)
      if(line =~/assembly: AssemblyFileVersion\(\"(.*)\"/)
        assemblyVersion =$1 + "-"
        break
      end
    end
    chdir("Nsis_Installer")
    value = `cmd.exe /c MakeBuildAndInstaller.cmd`
    @@log.info(value)
    source = "RollbackSetup.exe"
    target = "RollbackSetup-" + assemblyVersion + svnVersionNumber + ".exe"
    if(File.exist?(target))
      File.unlink(target)
    end
    File.rename(source,target)
    @@log.info("Created installer <"+target+">. Size=" + File.size(target).to_s() + "  " + File.mtime(target).to_s())
  end
end

def main
  # create the builder object
  builder = Builder.new(
                "https://rollback.svn.codeplex.com/svn",
                "C:/cygwin/bin/",
                "build",
                "password",
                "../../",
                "rollback")
  deleteExisting = false
  builder.updateOrCheckoutProject( deleteExisting )
  version = builder.updateSvnInfoInSourceCode()
  builder.makeInstaller(version)
end


main()